package com.njtoyo.taxi.admin.rest.controller.business.driver;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.map.MapUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njtoyo.taxi.admin.aop.PassToken;
import com.njtoyo.taxi.admin.aop.PermissionScope;
import com.njtoyo.taxi.admin.mapper.master.entity.Driver;
import com.njtoyo.taxi.admin.rest.presenter.business.driver.*;
import com.njtoyo.taxi.admin.rest.presenter.business.taxis.TaxisPresenter;
import com.njtoyo.taxi.admin.rest.wrapper.business.canton.RegionUpdateWrapper;
import com.njtoyo.taxi.admin.rest.wrapper.business.driver.*;
import com.njtoyo.taxi.admin.service.business.driver.DriverService;
import com.njtoyo.taxi.entity.backend.AdminUser;
import com.taxi.entity.common.RestResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.CellStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("business/driver")
@Api(tags = {"司机管理"})
public class DriverController {

    @Autowired
    private DriverService driverService;

    @GetMapping()
    @ApiOperation(value = "司机列表", notes = "司机列表，权限：driver_list")
    @PermissionScope(names = {"driver_list"})
    RestResult<Page<DriverListPresenter>> index(@ModelAttribute("admin") AdminUser adminUser, @Valid DriverQueryWrapper wrapper) {
        return driverService.getList(adminUser, wrapper);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "司机详情", notes = "司机详情，权限：driver_details")
    @PermissionScope(names = {"driver_details"})
    RestResult<DriverDetailsPresenter> driverDetails(@PathVariable("id") Long id) {
        return driverService.driverDetails(id);
    }

    @PatchMapping("/{id}")
    @ApiOperation(value = "修改司机信息", notes = "修改司机姓名，权限：driver_information")
    @PermissionScope(names = {"driver_information"})
    RestResult updateDriverInformation(@PathVariable("id") Long id, @Valid @RequestBody UpdateDriverInformationWrapper updateDriverNameWrapper) {
        return driverService.updateDriverInformation(id, updateDriverNameWrapper);
    }

    @PatchMapping("/{id}/taxi")
    @ApiOperation(value = "司机换车", notes = "司机换车，权限：driver_switch_taxi")
    @PermissionScope(names = {"driver_switch_taxi"})
    RestResult updatePlateNumber(@PathVariable("id") Long id, @Valid @RequestBody UpdatePlateNumberWrapper updateDriverNameWrapper) {
        return driverService.updatePlateNumber(id, updateDriverNameWrapper);
    }

    @PatchMapping("/{id}/mobile-number")
    @ApiOperation(value = "司机换手机号", notes = "司机换手机号，权限：driver_mobile_number")
    @PermissionScope(names = {"driver_mobile_number"})
    RestResult updatePhoneNumber(@PathVariable("id") Long id, @Valid @RequestBody UpdatePhoneNumberWrapper updatePhoneNumberWrapper) {
        return driverService.updatePhoneNumber(id, updatePhoneNumberWrapper);
    }

    @PatchMapping("/{id}/updateRegion")
    RestResult updateRegion(@PathVariable("id") Long id, @Valid @RequestBody UpdateDriverRegionWrapper updateDriverRegionWrapper) {
        return driverService.updateRegion(id, updateDriverRegionWrapper);
    }

    @PatchMapping("/{id}/password")
    @ApiOperation(value = "司机重置密码", notes = "司机重置密码，权限：driver_reset_password")
    @PermissionScope(names = {"driver_reset_password"})
    RestResult updatePassword(@PathVariable("id") Long id) {
        return driverService.updatePassword(id);
    }

    @DeleteMapping("/cache")
    @ApiOperation(value = "司机批量清除缓存", notes = "司机批量清除缓存，权限：driver_clear_cache")
    @PermissionScope(names = {"driver_clear_cache"})
    RestResult deleteCache(@Valid DeleteCaheWrapper wrapper) {
        return driverService.deleteCache(wrapper);
    }

    @PatchMapping("/taxi/batch")
    @ApiOperation(value = "司机批量换车牌", notes = "上传excel,司机批量换车牌，权限：batch_switch_taxis,模板文件：DriverBatchChangeTaxi.xls")
    @PermissionScope(names = {"batch_switch_taxis"})
    RestResult updateSwitchTaxis(@RequestParam(value = "file", required = true) MultipartFile file) throws IOException {
        return driverService.updateSwitchTaxis(file);
    }

    @PostMapping()
    @ApiOperation(value = "注册司机", notes = "注册司机，权限：driver_register")
    @PermissionScope(names = {"driver_register"})
    RestResult register(@Valid @RequestBody DriverRegisterWrapper wrapper) {
        return driverService.register(wrapper);
    }

    @PostMapping("batch-register")
    @ApiOperation(value = "批量注册司机", notes = "上传excel，批量注册司机，权限：driver_batch_register, 模板文件：DriverRegister.xlsx")
    @PermissionScope(names = {"driver_batch_register"})
    RestResult batchRegister(@RequestParam(value = "file", required = true) MultipartFile file, @RequestParam(value = "cityId", required = true) Long cityId) throws IOException {
        DriverBatchRegisterWrapper wrapper = new DriverBatchRegisterWrapper();
        wrapper.setCityId(cityId);
        return driverService.batchRegister(file, wrapper);
    }

    @PatchMapping("/{id}/leave")
    @ApiOperation(value = "司机离职", notes = "司机离职，权限：driver_leave")
    @PermissionScope(names = {"driver_leave"})
    RestResult leave(@PathVariable("id") Long id, @Valid @RequestBody LeaveDateWrapper leaveWrapper) {
        return driverService.leave(id, leaveWrapper);
    }

    @PatchMapping("/{id}/unleave")
    @PermissionScope(names = {"driver_leave"})
    RestResult<?> unleave(@PathVariable("id") Long id) {
        return driverService.unleave(id);
    }

    @GetMapping("/query_like")
    @ApiOperation(value = "司机列表模糊查询", notes = "无权限")
    RestResult<List<DriverQueryLikeListPresenter>> index(@Valid DriverLikeQueryWrapper wrapper) {
        return driverService.getListLike(wrapper);
    }

    @GetMapping("/ride-click-farming")
    @ApiOperation(value = "刷单司机名单", notes = "刷单司机名单，权限：driver_ride_click_farming_list")
    @PermissionScope(names = {"driver_ride_click_farming_list"})
    RestResult<List<DriverQueryRideClickFarmingListPresenter>> rideClickFarming(@Valid RideClickFarmingQueryWrapper wrapper) {
        return driverService.getRideClickFarmingList(wrapper);
    }

    @GetMapping("/ride-click-farming/export")
    @ApiOperation(value = "刷单司机名单导出", notes = "刷单司机名单导出,权限：driver_ride_click_farming_export")
    @PermissionScope(names = {"driver_ride_click_farming_export"})
    public void rideClickFarmingExport(@Valid RideClickFarmingQueryWrapper wrapper, HttpServletResponse response) throws IOException {
        driverService.rideClickFarmingExport(wrapper, response);
    }

    @GetMapping("/export")
    @ApiOperation(value = "司机列表Excel导出", notes = "司机列表Excel导出，权限：driver_export")
    @PermissionScope(names = {"driver_export"})
    public void exportDriver(@ModelAttribute("admin") AdminUser adminUser, @Valid DriverQueryWrapper wrapper, HttpServletResponse response) throws IOException {
        wrapper.setSize(100000);
        RestResult<Page<DriverListPresenter>> restResult = driverService.getList(adminUser, wrapper);
        List<DriverListPresenter> pages = restResult.getData().getRecords();
        List<Map<String, Object>> rows = new ArrayList<>();
        if (CollUtil.isNotEmpty(pages)) {
            for (DriverListPresenter presenter : pages) {
                Map<String, Object> row = new HashMap<>();
                row.put("编号", presenter.getId());
                row.put("姓名", presenter.getName());
                row.put("手机号", presenter.getMobileNumber());
                row.put("从业资格证", presenter.getQualificationCertificateNumber());
                row.put("车牌", presenter.getTaxiPlatNumber());
                row.put("地区", presenter.getCantonName());
                row.put("运力公司", presenter.getCompanyName());
                row.put("入住时间", presenter.getCreatedAt().toString());
                row.put("APP状态", presenter.getInService() ? "在线" : "未在线");
                row.put("车机版本号", presenter.getVersion());
                row.put("在职状态", presenter.getIsLeave() ? "离职" : "在职");
                row.put("平台封禁状态", presenter.getIsActive() ? "正常" : "封禁");
                rows.add(row);
            }
        } else {
            Map<String, Object> row = new HashMap<>();
            row.put("编号", "");
            row.put("姓名", "");
            row.put("手机号", "");
            row.put("从业资格证", "");
            row.put("车牌", "");
            row.put("地区", "");
            row.put("运力公司", "");
            row.put("入住时间", "");
            row.put("APP状态", "");
            row.put("车机版本号", "");
            row.put("在职状态", "");
            row.put("平台封禁状态", "");
            rows.add(row);
        }
        ExcelWriter writer = ExcelUtil.getWriter();
        StyleSet style = writer.getStyleSet();
        CellStyle cellStyle = style.getHeadCellStyle();
        cellStyle.setWrapText(true);
        writer.write(rows, true);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=cars.xls");
        ServletOutputStream out = response.getOutputStream();

        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }

    @PatchMapping("/unblock-lock")
    @ApiOperation(value = "司机批量冻解封", notes = "司机批量解封，权限：driver_unlock")
    @PermissionScope(names = {"driver_unlock"})
    RestResult batchUnblock(@Valid @RequestBody DriverBatchUnblockWrapper driverBatchUnblockWrapper) {
        return driverService.batchIsBlock(driverBatchUnblockWrapper);
    }

    @GetMapping("/{id}/service-state")
    @ApiOperation(value = "获取司机出车状态", notes = "获取司机出车状态，权限：driver_set_offline")
    @PermissionScope(names = {"driver_set_offline"})
    RestResult<DriverServiceStatePresenter> getServiceState(@PathVariable("id") Long id) {
        return driverService.getServiceState(id);
    }

    @PatchMapping("/{id}/offline")
    @ApiOperation(value = "强制司机收车", notes = "强制司机收车, 权限：driver_set_offline")
    @PermissionScope(names = {"driver_set_offline"})
    RestResult setOffline(@PathVariable("id") Long id) {
        return driverService.setOffline(id);
    }

    @GetMapping("/{id}/account")
    @ApiOperation(value = "司机账户统计", notes = "司机财务账户统计，权限：driver_details")
    @PermissionScope(names = {"driver_details"})
    RestResult<DriverAccountPresenter> account(@PathVariable("id") Long id) {
        return driverService.getAccount(id);
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除司机", notes = "删除司机，权限：driver_delete")
    @PermissionScope(names = {"driver_delete"})
    RestResult deleteDriver(@PathVariable("id") Long id) {
        return driverService.deleteDriver(id);
    }

    @GetMapping("/{id}/recommendation")
    @ApiOperation(value = "指定司机推广记录", notes = "指定司机推广记录，权限： driver_promotion_of_record")
    @PermissionScope(names = {"driver_promotion_of_record"})
    RestResult<IPage<DriverRecommendationListPresenter>> recommendation(@PathVariable("id") Long id, @Valid DriverRecommendationQueryWrapper wrapper) {
        return driverService.getRecommendationList(id, wrapper);
    }

    @GetMapping("/recommendation/{id}")
    @ApiOperation(value = "推广记录详情", notes = "推广记录详情，权限： driver_promotion_of_record")
    @PermissionScope(names = {"driver_promotion_of_record"})
    RestResult<RecommendationDetailPresenter> recommendationDetail(@PathVariable("id") Long id) {
        return driverService.getRecommendationDetail(id);
    }

    @GetMapping("/{id}/simple-info")
    @ApiOperation(value = "司机简单信息", notes = "")
    RestResult<DriverSimpleInfoPresenter> simpleInfo(@PathVariable("id") Long id) {
        return driverService.simpleInfo(id);
    }

    @PostMapping("/compensate/recommender")
    @ApiOperation(value = "新乘客激活给推荐人发奖励", notes = "权限：driver_promotion_send_reward")
    @PermissionScope(names = {"driver_promotion_send_reward"})
    RestResult compensateRecommender(@Valid @RequestBody compensateCustomerWrapper wrapper) {
        return driverService.compensateRecommender(wrapper);
    }

    @PostMapping("/compensate/first/ride")
    @ApiOperation(value = "乘客首单给推荐人发奖励", notes = "权限：driver_promotion_send_reward")
    @PermissionScope(names = {"driver_promotion_send_reward"})
    RestResult compensateCustomerFirstRide(@Valid @RequestBody compensateCustomerWrapper wrapper) {
        return driverService.compensateCustomerFirstRide(wrapper);
    }

    @GetMapping("/{id}/recommendation/driver")
    @ApiOperation(value = "指定司机推广司机的记录", notes = "指定司机推广司机的记录，权限： driver_to_driver_promotion_of_record")
    @PermissionScope(names = {"driver_to_driver_promotion_of_record"})
    RestResult<IPage<DriverRecommendationDriverListPresenter>> recommendationDriver(@PathVariable("id") Long id, @Valid DriverRecommendationDriverQueryWrapper wrapper) {
        return driverService.getRecommendationDriverList(id, wrapper);
    }

    @GetMapping("/{driverId}/recommend-task")
    @ApiOperation(value = "司机推广任务奖励", notes = "司机推广任务奖励，权限：driver_recommend_task")
    @PermissionScope(names = {"driver_recommend_task"})
    RestResult<IPage<DriverRecommendTaskListPresenter>> driverTask(@PathVariable("driverId") Long driverId, DriverRecommendTaskListQueryWrapper wrapper) {
        return driverService.driverTask(driverId, wrapper);
    }

    @GetMapping("/recommend-task/{id}")
    @ApiOperation(value = "司机推广任务奖励-详情", notes = "司机推广任务奖励，权限：driver_recommend_task")
    @PermissionScope(names = {"driver_recommend_task"})
    RestResult<DriverRecommendTaskDetailPresenter> driverTaskDetail(@PathVariable("id") Long id) {
        return driverService.driverTaskDetail(id);
    }


    @GetMapping("/getAutomaticList")
    @PassToken
    RestResult list(@ModelAttribute("admin") AdminUser adminUser, @Valid DriverQueryWrapper wrapper) {
        return driverService.getAutomaticList(adminUser, wrapper);
    }


    /**
     * 关闭自动抢单
     *
     * @return
     */
    @PostMapping("/closeAutomatic")
    @PassToken
    RestResult closeAutomatic(@RequestBody Dict params) {
        String ids = MapUtil.getStr(params, "ids");
        return driverService.closeAutomatic(ids);
    }

    /**
     * 开启自动抢单
     *
     * @return
     */
    @PostMapping("/openAutomatic")
    @PassToken
    RestResult openAutomatic(@RequestBody Dict params) {
        String ids = MapUtil.getStr(params, "ids");
        return driverService.openAutomatic(ids);
    }


    /**
     * 根据车牌号查询司机
     *
     * @return
     */
    @GetMapping("/queryByTaxi/{plateNumber}")
    RestResult queryByTaxi(@PathVariable("plateNumber") String plateNumber) {
        return driverService.queryByTaxi(plateNumber);
    }

    /**
     * 根据车牌号查询司机
     *
     * @return
     */
    @GetMapping("/queryByName")
    RestResult queryByName(@RequestParam(value = "driverName", required = false) String driverName) {
        return driverService.queryByName(driverName);
    }


}
